<?php

/**
 * unicodeToUTF8
 * convert Unicode codepoint (json) to human read format
 *
 * @see http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
 * @param  [type] $str
 * @return [type]
 */
function unicodeToUTF8($str)
{
    // preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
    //     return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
    // }, $str);
    // In case it's UTF-16 based C/C++/Java/Json-style:
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
    }, $str);
}

/**
 * utf8字符转换成Unicode字符
 * @param  string $utf8_str Utf-8字符
 * @return string           Unicode字符
 * @see https://segmentfault.com/a/1190000003020776
 */
function utf8_to_unicode($utf8_str)
{
    $unicode = 0;
    $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
    $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
    $unicode |= (ord($utf8_str[2]) & 0x3F);
    return dechex($unicode);
}

/**
 * utf8_str_to_unicode
 *
 * @param  string $str
 * @return array
 */
function utf8_str_to_unicode($str)
{
    $str_arr = preg_split('//u',$str, -1, PREG_SPLIT_NO_EMPTY);
    $codes = [];
    foreach ($str_arr as $key => $val) {
        $codes[] = utf8_to_unicode($val);
    }
    return $codes;
}

/**
 * Unicode字符转换成utf8字符
 * @param  string $unicode_str Unicode字符
 * @return string              Utf-8字符
 */
function unicode_to_utf8($unicode_str)
{
    $utf8_str = '';
    $code = intval(hexdec($unicode_str));
    //这里注意转换出来的code一定得是整形，这样才会正确的按位操作
    $ord_1 = decbin(0xe0 | ($code >> 12));
    $ord_2 = decbin(0x80 | (($code >> 6) & 0x3f));
    $ord_3 = decbin(0x80 | ($code & 0x3f));
    $utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
    return $utf8_str;
}
